<template>
  <div>
    <div style="margin-left: 86%;">
      <el-button @click="downloadLine" icon="el-icon-download">下载</el-button>
    </div>
    <div
      class="echart"
      ref="mychart"
      id="mychart"
      :style="{ float: 'left', width: '100%', height: '366px' , background: '#fff'}"
    ></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import bus from '@/views/dashboard/bus';

export default {
  data() {
    return {
      rows: []
    };
  },
  mounted() {
    bus.$on('lineData', data => {
      this.rows = data;
      this.initEcharts();
    });
  },
  methods: {
    getMonthDiff(year, month, day, mon) {
      if (month - mon < 0) {
        month = 12 + (month - mon);
        year -= 1;
      } else if (month - mon > 12) {
        month = month - mon - 12;
        year += 1;
      } else {
        month = month - mon;
      }
      var days = new Date(year, month, 0).getDate();
      if (day > days - 1) {
        day = days - 1;
      }
      return `${year}-${month}-${day}`;
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
    },
    initEcharts() {
      // 今天
      const today_time = new Date();
      const today_year = today_time.getFullYear();
      const today_month = today_time.getMonth() + 1;
      const today_day = today_time.getDate();
      const today =today_year + "-" + today_month + "-" + today_day;

      // 半年前的某一天
      const sixMonthAgo = this.getMonthDiff(today_year,today_month,today_day,6);

      // 半年内的每一天
      var sixMonthsDates = [];
      var date = new Date(sixMonthAgo);

      while (date <= today_time) {
        sixMonthsDates.push([[this.formatDate(date)],[],[],[],[],[]]); // 格式化日期并添加到数组中
        date.setDate(date.getDate() + 1); // 增加一天，准备下一次循环
      }

      // 创建一个对象来存储每个日期的数据
      const dataByDate = {};
      this.rows.forEach(row => {
        const date = row.create_time; // 假设 create_time 是 'YYYY-MM-DD' 格式
        dataByDate[date] = row;
      });

      // 遍历 sixMonthsDates 并在内部数组中存储计算的值
      sixMonthsDates.forEach(dateArray => {
        const date = dateArray[0][0]; // 获取日期
        const data = dataByDate[date]; // 查找对应的数据

        if (data) {
          // 如果有数据，计算并存储值
          dateArray[1] = data.multimodal + data.article; // 总资源
          dateArray[2] = data.multimodal_image; // 图片
          dateArray[3] = data.multimodal_video; // 视频
          dateArray[4] = data.multimodal_audio; // 音频
          dateArray[5] = data.multimodal_text + data.article; // 文本
        } else {
          // 如果没有数据，填充空值
          dateArray[1] = 0; // 总资源
          dateArray[2] = 0; // 图片
          dateArray[3] = 0; // 视频
          dateArray[4] = 0; // 音频
          dateArray[5] = 0; // 文本
        }
      });

      const option = {
        // 标题
        title: {
          text: "科普资源增量",
          top: "3%",
          left: "center",
        },
        // 图例
        legend: {
          data: [
            { name: '总资源', icon: 'circle' },
            { name: '图片', icon: 'circle' },
            { name: '视频', icon: 'circle' },
            { name: '音频', icon: 'circle' },
            { name: '文本', icon: 'circle' }
          ],
          left: 'center',
          top: "auto",
          bottom: "3%", // 调整图例距离底部的位置
          orient: "horizontal", // 设置图例为水平布局
        },
        // 提示框
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: function (params) {
            let tooltipContent = params[0].name + '<br />';
            params.forEach(param => {
              tooltipContent += param.marker + param.seriesName + ': ' + param.value + '<br />'; // 每条线的数据值
            });
            return tooltipContent;
          },
        },
        xAxis: {
          data: sixMonthsDates.map(item => item[0]),
          name: "日期",
          // data: this.rows.map(item => item.create_time),
        },
        yAxis: {
          type: 'value',
          name: '增量',
          axisLabel: {
            formatter: '{value}'
          },
        },
        series: [
          {
            name: '总资源',
            data: sixMonthsDates.map(item => item[1]),
            type: 'line',
          },
          {
            name: '图片',
            data: sixMonthsDates.map(item => item[2]),
            type: 'line',
          },
          {
            name: '视频',
            data: sixMonthsDates.map(item => item[3]),
            type: 'line',
          },
          {
            name: '音频',
            data: sixMonthsDates.map(item => item[4]),
            type: 'line',
          },
          {
            name: '文本',
            data: sixMonthsDates.map(item => item[5]),
            type: 'line',
          }
        ]
      };
      this.myChart = echarts.init(this.$refs.mychart);
      this.myChart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },
    downloadLine() {
      // 获取画布信息
      let canvas = document.getElementsByTagName("canvas");
      if(canvas&&canvas.length>0){
          // 创建标签
          let tempA = document.createElement("a");
          // 设置下载名称
          tempA.download = "科普资源增量图" +".png";
          // 设置地址以及文件类型
          tempA.href = canvas[0].toDataURL("image/png");
          document.body.appendChild(tempA);
          tempA.click();
          tempA.remove();
      }
    },
  },
  created(){
    this.getMonthDiff();
    this.formatDate()
  }
};
</script>